import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'

export const usePlayStore = defineStore(
  'playInfo',
  () => {
    // 播放列表
    const playlist = ref([])
    // 当前播放音乐列表位置
    const playIndex = ref(0)
    // 当前播放状态
    const isPlayer = ref(true)
    // 歌曲详情弹出层
    const musicDialog = ref(false)
    // 当前播放音乐地址
    const currSongUrl = ref('')
    // 当前播放时间
    const currentTime = ref(0)
    // 音频引用
    const audioRef = ref(null)
    // 音频信息
    const info = reactive({
      // 初始化音频准备
      initAudioReady: false,
      // 播放模式  0循环播放、1单曲循环、2随机播放
      playMode: 0
    })
    // 当前播放列表
    const isShowPopup = ref(false)
    // 搜索关键字
    const searchKey = ref('')

    // 设置播放状态
    const setPlayStatus = (val = false) => (isPlayer.value = val)
    // 播放当前选择的音乐
    const setPlaylist = (val) => playlist.value = val
    // 设置当前播放歌曲下标
    const setPlayIndex = (val = 0) => {
      playIndex.value = val
      window.localStorage.setItem('playIndex', val)
    }

    // 显示/隐藏歌曲详情弹出层
    const changeMusicDialog = () => (musicDialog.value = !musicDialog.value)
    // 设置当前播放时间
    const setCurrentTime = (val) => currentTime.value = val

    const findIndexs = (list, playList) => playList.findIndex(d => d.id === list.id)

    // 合并歌曲到播放列表查重
    const concatPlayList = (list, playList = []) => {
      return concatPlayLists(list, playList)
    }
    const concatPlayLists = (newList = [], oldList = []) => {
      const arr = [...oldList, ...newList]
      const map = new Map()
      for (const item of arr) {
        if (!map.has(item.id)) map.set(item.id, item)
      }
      return [...map.values()]
    }
    // 播放当前选中的音乐
    const selectPlay = (list) => {
      if (!audioRef.value) return
      const playList = concatPlayList(list, playlist.value)
      // 更新播放列表
      setPlaylist(playList)
      // 获取要比方的音乐在播放列表中的索引
      const playIndex = findIndexs(list[0], playList)
      // 设置当前播放音乐的索引
      setPlayIndex(playIndex)
      // 设置当前播放音乐的URL
      currSongUrl.value = playList[playIndex].url
      // 设置音频源 
      audioRef.value.src = currSongUrl.value
      // 播放音乐
      audioRef.value.play().catch(() => { })
    }
    // 显示/隐藏当前播放列表
    const setShowPopup = (val) => isShowPopup.value = val
    return {
      playlist,
      playIndex,
      isPlayer,
      musicDialog,
      currSongUrl,
      currentTime,
      audioRef,
      info,
      isShowPopup,
      setPlayStatus,
      setPlaylist,
      setPlayIndex,
      changeMusicDialog,
      setCurrentTime,
      findIndexs,
      concatPlayList,
      selectPlay,
      setShowPopup,
      searchKey
    }
  },
  { persist: true }
)
